import logging
import os
import time
from logging import handlers

# 浏览器复用选项
# chrome -remote-debugging-port=9330
import allure
from selenium.webdriver.common.by import By

global CHROME_REUSE

# 基础路径地址
BASE_DIR = os.path.dirname(os.path.abspath(__file__))


# 初始化日志函数
def init_logging():
    # 创建日志器
    logger = logging.getLogger()
    # 设置日志等级
    logger.setLevel(logging.DEBUG)

    # 设置处理器
    # 控制台处理器:控制把日志输出道控制台
    sf = logging.StreamHandler()

    # 文件处理器:吧日志输出到外部文件当中,需要提前定义文件的丼和文件名成
    logname = os.path.dirname(os.path.abspath(__file__)) + '/log/log.log'
    fh = logging.handlers.TimedRotatingFileHandler(logname, when='midnight', interval=1, backupCount=7,
                                                   encoding='utf-8')
    sf.setLevel(logging.DEBUG)
    fh.setLevel(logging.INFO)
    # 设置格式化器
    fmt = "%(asctime)s %(levelname)s [%(name)s] [%(filename)s(%(funcName)s:%(lineno)d)] - %(message)s"
    formatter = logging.Formatter(fmt)
    # 将格式化器添加到处理器当中
    sf.setFormatter(formatter)
    fh.setFormatter(formatter)
    # 将处理器添加到日至器当中
    logger.addHandler(sf)
    logger.addHandler(fh)

# def param(a)
#     def extend(func):
#         def wrapper(*args, **kwargs):
#             print(a)
#             print('---')
#             return func(*args, **kwargs)
#         return wrapper
#     return extend


# 装饰器函数
def handle_black(func):
    def wrapper(*args, **kwargs):
        from base.base_page import BasePage

        _black_list = [
            (By.XPATH, '//*[contains(@text, "确认")]'),
            (By.XPATH, '//*[contains(@text, "确定")]'),
            (By.XPATH, '//*[contains(@text, "好")]'),
        ]
        _max_num = 3
        _error_num = 0
        instance: BasePage = args[0]

        try:
            logging.info('\n正在运行===> '+func.__name__ + "\n 参数为: "+repr(args[1:])+"\n 键值对: "+repr(kwargs)+"\n")
            element = func(*args, **kwargs)
            _error_num = 0
            return element

        except Exception as ex:
            # 错误截图
            # allure.attach(instance.screenshot('未获取到元素'), allure.attachment_type.PNG)
            instance.allure_screenshot('未找到元素')
            logging.warning('\n<========元素信息未获取到, 开始寻找黑名单信息========>\n')
            if _error_num > _max_num:
                raise ex
            _error_num += 1
            for tur_ele in _black_list:
                ele_list = instance._driver.find_elements(*tur_ele)
                if len(ele_list) > 0:
                    ele_list[0].click()
                    logging.info('\n<========已寻找到遮罩信息:第{}个遮罩, 并点击处理========>\n'.format(_black_list.index(tur_ele)))
                    return wrapper(*args, **kwargs)
            logging.warning('\n<========未找到元素, 黑名单中未找到遮罩相关信息========>\n')
            raise ex

    return wrapper



